package com.xqboss.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里实名认证
 *
 * @author Administrator
 */
@Slf4j
public class AliIdentityUtil {

    /**
     * 身份证号码+真实姓名二要素验证
     *
     * @param appCode
     * @param cardNo   身份证号码
     * @param realName 真实姓名
     */
    public static Boolean cardNoAndRealName(String appCode, String cardNo, String realName) {
        String host = "https://zid.market.alicloudapi.com";
        String path = "/idcard/VerifyIdcardv2";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("cardNo", cardNo);
        querys.put("realName", realName);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            JSONObject responseObj = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            //获取验证结果
            JSONObject resultObj = JSONObject.parseObject(responseObj.get("result") + "");
            // 获取是否成功
            log.info("身份证校验 获取是否成功: {}", response);
            return Boolean.parseBoolean(resultObj.get("isok") + "");
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            log.error("~~~~~~~~~~~~~~~~~~~~~~~~~实名认证二要素验证失败", e);
            throw new ServiceException("实名认证失败, 请联系客服");
        }
    }

    public static void main(String[] args) {
        System.out.println(cardNoAndRealName("6a22e2f9957d4e49b8fd17406d17fd30", "", ""));
    }
}
